#!/bin/bash

if [[ 0 -eq $# ]]
then
	echo Install Script:
	echo "  start         start the nginx."
	echo "  restart       stop then start the nginx."
	echo "  stop          stop the nginx."
	echo "  make          make and make install."
	echo "  new-install   clean, configure, make and make install."
	echo
	exit
fi

# nginx src path
NGX_PATH=~/Documents/source/nginx-1.1.6
# nginx install path
NGX_INS_PATH=/usr/local/nginx

if [[ ! -d $NGX_PATH ]]
then
	echo Wrong NGX_PATH
fi

cd $NGX_PATH

for ARG in $*
do
	if [[ "new-install" == $ARG ]]
	then
		make clean
		CFLAGS="-g -O0" ./configure
			break
	fi
done

NO_MK=F
for ARG in $*
do
	if [[ "no-make"  == $ARG ]]
	then
		NO_MK=T
		echo No Make...
		break;
	fi
done

if [[ 'F' == $NO_MK ]]
then
	for ARG in $*
	do
		if [[ "make"  == $ARG || "new-install" == $ARG ]]
		then
			make  -j 8 && make install
		break
		fi
	done
fi

for ARG in $*
do
	if [[ "start" == $ARG ]]
	then
		echo "Starting nginx && php-cgi..."
		sudo /usr/local/bin/spawn-fcgi -C 2 -p 9000 -f php-cgi
		$NGX_INS_PATH/sbin/nginx && echo done.
		break
	fi
done

for ARG in $*
do
	if [[ "restart" == $ARG ]]
	then
		echo "Killing nginx && php-cgi processes..."
		sudo kill -9 $(ps axu | grep php-cgi | grep -v grep | awk '{print $2}')
		killall nginx && echo done.
		sleep 1
		echo Starting...
		sudo /usr/local/bin/spawn-fcgi -C 2 -p 9000 -f php-cgi
		$NGX_INS_PATH/sbin/nginx && echo done.
		break
	fi
done

for ARG in $*
do
	if [[ "stop" == $ARG ]]
	then
		echo "Killing nginx processes && php-cgi..."
		sudo kill -9 $(ps axu | grep php-cgi | grep -v grep | awk '{print $2}')
		killall nginx && echo done.
		break
	fi
done

cd -

